package com.jiazhong.front.filter;

import com.jiazhong.commons.config.JwtConfig;
import com.jiazhong.commons.exception.NotLoginException;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

@Component
@Slf4j
public class IsLoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        log.info("开始校验用户是否登录");
        //1.获取用户的token
        String token = request.getHeader("token");
        log.info("token:{}",token);
        //2.校验token是否合法
        boolean b = JwtConfig.checkToken(token);
        log.info("b:{}",b);
        if (!b){
            throw new NotLoginException("用户没有登陆");
        }
        //获取到redis中的token
        Claims claims = JwtConfig.parseJWT(token);
        Object id = claims.get("id");
        String key = "front_token:" + id;
        String redisToken = stringRedisTemplate.opsForValue().get(key);
        log.info("id:{},key:{},redisToken:{}",id,key,redisToken);
        //4.校验是否一致
        if (!Objects.equals(token,redisToken)){
            throw new NotLoginException("用户没有登陆");
        }
        log.info("用户已登录");
        return true;
    }
}
